package net.superdvach.content;

import net.superdvach.core.Config;

import java.io.IOException;
import java.sql.*;

public class JDBCStorage implements ContentStorage {

	public JDBCStorage(Config config) throws ClassNotFoundException {
		try {
			Class.forName("org.postgresql.Driver");
			m_dbConnection = DriverManager.getConnection("jdbc:postgresql:"
					+ config.getProperty("dbname", "s2ch"), config.getProperty(
					"dbuser", "s2ch"), config.getProperty("dbpassword"));

			if (!isTableExists("items")) {
				createItemsTable();
			}

		} catch (SQLException e) {
			System.out.println("Database error: " + e.getMessage());
		}
	}

	@Override
	public void collectGarbage() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public Item loadItem(ItemID id) {
		try {
			Statement st = m_dbConnection.createStatement();
			ResultSet rs = st.executeQuery("SELECT * FROM items WHERE id='" + id.toString() + "'");
			return ItemFactory.makeItem(rs.getBytes(3));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void setPassword(String pass) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void storeItem(Item item) {
		try {
			PreparedStatement st = m_dbConnection.prepareStatement("INSERT INTO items VALUES(?, ?, ?)");
			st.setString(1, item.id().toString());
			st.setString(2, item.type());
			st.setBytes(3, item.serialize());
		}
		catch(SQLException e) {
			// Ignore
		}
		catch(IOException e) {
			// Like i care
		}
		
	}
	
	private void createItemsTable() throws SQLException {
		Statement st = m_dbConnection.createStatement();
		st.execute("CREATE TABLE items (id char(128), type char(32), data bytea);");
		st.close();
	}

	private boolean isTableExists(String name) {
		try {
			Statement st = m_dbConnection.createStatement();
			st.executeQuery("SELECT COUNT(*) FROM " + name);
			return true;
		} catch (SQLException e) {
			return false;
		}
	}

	private Connection m_dbConnection;

}
